import 'package:cbec_app/components/base/base_customize_segmented_control.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/count_down_timer.dart';
import 'package:cbec_app/components/common/not_found.dart';
import 'package:cbec_app/pages/goods/controller/group_buying_ctr.dart';
import 'package:cbec_app/pages/goods/entity/activity_item_entity.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../binding/goods_detail_binding.dart';
import 'goods_detail_page.dart';

//团购页面
class GroupBuyingPage extends GetView<GroupBuyingController> {
  const GroupBuyingPage({super.key});

  List<Widget> _createItemWidgets() {
    final GroupBuyingController controller = Get.find<GroupBuyingController>();
    List<Widget> widgetArr = [];
    for (int i = 0; i < controller.itemList.length; i++) {
      ActivityItemEntity item = controller.itemList[i];
      int selectIndex = controller.selected;
      if (i == 0) {
        widgetArr.add(
          Container(
            padding: const EdgeInsets.only(left: 5, top: 5, bottom: 0, right: 5),
            child: Column(
              // mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CountDownTimer(
                  timeStamp: DateTime.parse(item.endtime ?? '').millisecondsSinceEpoch,
                  timeStyle: TimeStyle.hhmmss,
                  countDownStyle: CountDownStyle.box,
                  boxBackgroundColor: Tools.fromHex("#000000"),
                  colonColor: Tools.fromHex("#000000"),
                  style: setTextStyle(
                    12,
                    FontWeight.w400,
                    Tools.fromHex('#FFFFFF'),
                  ),
                  callback: () {},
                ),
                const SizedBox(
                  height: 5,
                ),
                Text(
                  '正在抢购',
                  style: TextStyle(
                    color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        widgetArr.add(
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                item.begintime ?? '',
                style: TextStyle(
                  color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                ),
              ),
              const SizedBox(
                height: 3,
              ),
              Text(
                '即将开始',
                style: TextStyle(color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'), fontWeight: FontWeight.w500, fontSize: 12),
              ),
            ],
          ),
        );
      }
    }
    return widgetArr;
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<GroupBuyingController>(builder: (controller) {
      return Scaffold(
        extendBodyBehindAppBar: true, // 允许 body 从 AppBar 顶部开始布局
        appBar: AppBar(
          backgroundColor: Colors.transparent, // 设置透明
          leading: IconButton(
            icon: const Icon(
              Icons.arrow_back,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        // backgroundColor: Tools.fromHex("#F74133"),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //自适应高度的图片
            SizedBox(
              width: double.infinity,
              child: Image.asset("assets/images/pingtuan_bg.png", fit: BoxFit.fitWidth),
            ),

            SizedBox(
              height: 60,
              child: BaseCustomizeSegmentedControl(
                  items: _createItemWidgets(),
                  selectedIndex: controller.selected,
                  onChanged: (index) {
                    controller.change(index);
                  }),
            ),

            Expanded(
              child: controller.goodsList.isNotEmpty
                  ? Tools.getPullRefresh(
                      enablePullDown: true,
                      enablePullUp: true,
                      refreshController: controller.baseRefreshCtr,
                      onRefresh: controller.onPageRefresh,
                      onLoading: controller.onPageLoading,
                      child: //列表
                          controller.style == 1
                              ?
                              //样式1
                              ListView.builder(
                                  controller: controller.scrollController,
                                  padding: EdgeInsets.only(top: 10.w),
                                  itemCount: controller.goodsList.length,
                                  itemBuilder: (context, index) {
                                    final Map item = controller.goodsList[index];
                                    return PintuanItem1(item: item);
                                  })
                              :
                              //样式2
                              GridView.count(
                                  controller: controller.scrollController,
                                  padding: EdgeInsets.all(10.w),
                                  childAspectRatio: 4 / 6,
                                  // physics: NeverScrollableScrollPhysics(),
                                  mainAxisSpacing: 10.w,
                                  crossAxisSpacing: 5.w,
                                  // shrinkWrap: true,
                                  crossAxisCount: 3,
                                  children: List.generate(controller.goodsList.length, (index) {
                                    final Map item = controller.goodsList[index];
                                    return PintuanItem2(item: item);
                                  }),
                                ))
                  : const NotFound(),
            )
          ],
        ),
      );
    });
  }
}

class GroupTabbar extends StatelessWidget {
  final GroupBuyingController controller = Get.find<GroupBuyingController>();
  GroupTabbar({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(left: 8.w, right: 8.w),
        height: 44.h,
        child: ListView.builder(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            itemCount: controller.itemList.length,
            itemBuilder: ((context, index) {
              return BaseInteractive(
                onClick: () => {controller.change(index)},
                childWidget: Container(
                  margin: EdgeInsets.only(right: 40.w),
                  child: Column(
                    children: [
                      Text(controller.itemList[index].begintime ?? '', style: setTextStyle(controller.selected == index ? 18 : 15, FontWeight.w700, Tools.fromHex("#FFFFFF"))),
                      SizedBox(height: 2.h),
                      Container(
                        decoration: border_radis(Tools.fromHex("#FDD595")),
                        padding: EdgeInsets.fromLTRB(4.w, 0.w, 4.w, 1.w),
                        child: controller.itemList[index].status == 2 ? Text("抢购中", style: setTextStyle(10, FontWeight.w500, Tools.fromHex("#FF3437"))) : Text("未开始", style: setTextStyle(10, FontWeight.w500, Tools.fromHex("#84420B"))),
                      )
                    ],
                  ),
                ),
              );
            })));
  }
}

//拼团ITEM样式2【一行三个】
class PintuanItem2 extends StatelessWidget {
  final Map item;

  const PintuanItem2({
    super.key,
    required this.item,
  });

  @override
  Widget build(BuildContext context) {
    return BaseInteractive(
      onClick: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      childWidget: Container(
        // margin: EdgeInsets.only(left: 8.w,right: 8.w),
        padding: EdgeInsets.all(8.w),
        decoration: border_radis(Colors.white),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            BaseImage(url: item['mainImage'], width: 96, height: 75),
            SizedBox(height: 5.w),
            Row(
              children: [
                groupPersonNumTag(item['num'].toString()),
                Container(
                  margin: EdgeInsets.only(left: 2.w),
                  width: 49.w,
                  child: Text(item['commodityName'], style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#333333")), overflow: TextOverflow.ellipsis),
                )
              ],
            ),
            SizedBox(height: 5.w),
            Text("拼单价${item['price'].toString()}", style: TextStyle(fontSize: 12, fontWeight: FontWeight.w300, color: Tools.fromHex("#999999"), decoration: TextDecoration.lineThrough, decorationColor: Tools.fromHex("#999999"))),
            SizedBox(height: 5.w),
            Container(
              width: 95.w,
              height: 26.h,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/pintuan_button_2.png'),
                  fit: BoxFit.fill,
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [Text("￥", style: setTextStyle(15, FontWeight.w700, Tools.fromHex("#FFFFFF"))), Text(item['specialPrice'].toString().split(".")[0], style: setTextStyle(18, FontWeight.w700, Tools.fromHex("#FFFFFF"))), Text(".${item['specialPrice'].toString().split(".")[1]}", style: setTextStyle(15, FontWeight.w700, Tools.fromHex("#FFFFFF")))],
              ),
            )
          ],
        ),
      ),
    );
  }
}

//拼团ITEM样式1【列表】
class PintuanItem1 extends StatelessWidget {
  final Map item;

  const PintuanItem1({
    super.key,
    required this.item,
  });

  @override
  Widget build(BuildContext context) {
    return BaseInteractive(
      onClick: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      childWidget: Container(
        padding: EdgeInsets.all(10.w),
        margin: EdgeInsets.only(left: 12.w, right: 12.w, bottom: 10.w),
        decoration: border_radis(Colors.white),
        child: Row(
          children: [
            Stack(
              children: [
                Positioned(
                    child: Container(
                  child: BaseImage(url: item['mainImage'], width: 116, height: 116),
                )),
                Positioned(child: groupPersonNumTag(item['num'].toString()))
              ],
            ),
            SizedBox(width: 10.w),
            //中间部分
            Container(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  item['commodityType'] == 0
                      ? goodsTypeTag("一般贸易")
                      : item['commodityType'] == 1
                          ? goodsTypeTag("保税")
                          : item['commodityType'] == 2
                              ? goodsTypeTag("海外直邮")
                              : emptyWidget(),
                  SizedBox(height: 6.h),
                  Text(item['brandName'], style: setTextStyle(14, FontWeight.w500, Tools.fromHex("#333333"))),
                  SizedBox(height: 4.h),
                  Container(
                    width: 190.w,
                    child: Text(
                      item['commodityName'],
                      style: setTextStyle(13, FontWeight.w500, Tools.fromHex("#666666")),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 2,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Text("剩余${item['storage'].toString()}件", style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#999999"))),
                  SizedBox(height: 8.h),
                  Container(
                    width: 190.w,
                    height: 32.h,
                    padding: EdgeInsets.all(8.w),
                    decoration: const BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage('assets/images/pintuan_button_1.png'),
                        fit: BoxFit.fill,
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [Text("￥", style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#FFFFFF"))), Text(item['specialPrice'].toString(), style: setTextStyle(14, FontWeight.w700, Tools.fromHex("#FFFFFF"))), SizedBox(width: 4.w), Text(item['price'].toString(), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w300, color: Tools.fromHex("FFFFFF"), decoration: TextDecoration.lineThrough, decorationColor: Tools.fromHex("#FFFFFF")))],
                        ),
                        Text("去开团", style: setTextStyle(15, FontWeight.w700, Tools.fromHex("#84420B")))
                      ],
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

//几人团标签
Widget groupPersonNumTag(String num) {
  return Container(
    padding: EdgeInsets.fromLTRB(4.w, 2.w, 4.w, 2.w),
    color: Tools.fromHex("#FDD595"),
    child: Text("${num}人团", style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#84420B"))),
  );
}
